/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System.ComponentModel;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace Oceanside
{
    public static class SortBehavior
    {
        public static readonly DependencyProperty CanUserSortColumnsProperty =
            DependencyProperty.RegisterAttached(
                "CanUserSortColumns",
                typeof(bool),
                typeof(SortBehavior),
                new FrameworkPropertyMetadata(OnCanUserSortColumnsChanged));

        public static readonly DependencyProperty CanUseSortProperty =
            DependencyProperty.RegisterAttached(
                "CanUseSort",
                typeof(bool),
                typeof(SortBehavior),
                new FrameworkPropertyMetadata(true));

        public static readonly DependencyProperty SortDirectionProperty =
            DependencyProperty.RegisterAttached(
                "SortDirection",
                typeof(ListSortDirection?),
                typeof(SortBehavior));

        public static readonly DependencyProperty SortExpressionProperty =
            DependencyProperty.RegisterAttached(
                "SortExpression",
                typeof(string),
                typeof(SortBehavior));

        [AttachedPropertyBrowsableForType(typeof(ListView))]
        public static bool GetCanUserSortColumns(ListView element)
        {
            try
            {
                if (element != null)
                {
                    return (bool)element.GetValue(CanUserSortColumnsProperty);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
            return false;
        }

        [AttachedPropertyBrowsableForType(typeof(ListView))]
        public static void SetCanUserSortColumns(ListView element, bool value)
        {
            try
            {
                if (element != null)
                {
                    element.SetValue(CanUserSortColumnsProperty, value);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
        }

        [AttachedPropertyBrowsableForType(typeof(GridViewColumn))]
        public static bool GetCanUseSort(GridViewColumn element)
        {
            try
            {
                if (element != null)
                {
                    return (bool)element.GetValue(CanUseSortProperty);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
            return false;
        }

        [AttachedPropertyBrowsableForType(typeof(GridViewColumn))]
        public static void SetCanUseSort(GridViewColumn element, bool value)
        {
            try
            {
                if (element != null)
                {
                    element.SetValue(CanUseSortProperty, value);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
        }

        [AttachedPropertyBrowsableForType(typeof(GridViewColumn))]
        public static ListSortDirection? GetSortDirection(GridViewColumn element)
        {
            try
            {
                if (element != null)
                {
                    return (ListSortDirection?)element.GetValue(SortDirectionProperty);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
            return null;
        }

        [AttachedPropertyBrowsableForType(typeof(GridViewColumn))]
        public static void SetSortDirection(GridViewColumn element, ListSortDirection? value)
        {
            try
            {
                if (element != null)
                {
                    element.SetValue(SortDirectionProperty, value);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
        }

        [AttachedPropertyBrowsableForType(typeof(GridViewColumn))]
        public static string GetSortExpression(GridViewColumn element)
        {
            try
            {
                if (element != null)
                {
                    return (string)element.GetValue(SortExpressionProperty);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
            return "";
        }

        [AttachedPropertyBrowsableForType(typeof(GridViewColumn))]
        public static void SetSortExpression(GridViewColumn element, string value)
        {
            try
            {
                if (element != null)
                {
                    element.SetValue(SortExpressionProperty, value);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
        }

        private static void OnCanUserSortColumnsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                var listView = d as ListView;
                if (listView != null)
                {
                    if ((bool)e.NewValue)
                    {
                        listView.AddHandler(GridViewColumnHeader.ClickEvent, (RoutedEventHandler)OnColumnHeaderClick);
                        if (listView.IsLoaded)
                        {
                            DoInitialSort(listView);
                        }
                        else
                        {
                            listView.Loaded += OnLoaded;
                        }
                    }
                    else
                    {
                        listView.RemoveHandler(GridViewColumnHeader.ClickEvent, (RoutedEventHandler)OnColumnHeaderClick);
                    }
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
        }

        private static void OnLoaded(object sender, RoutedEventArgs e)
        {
            try
            {
                var listView = e.Source as ListView;
                if (listView != null)
                {
                    listView.Loaded -= OnLoaded;
                    DoInitialSort(listView);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
        }

        private static void DoInitialSort(ListView listView)
        {
            try
            {
                var gridView = listView.View as GridView;
                if (gridView != null)
                {
                    var column = gridView.Columns.FirstOrDefault(c => GetSortDirection(c) != null);
                    if (column != null)
                    {
                        DoSort(listView, column);
                    }
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
        }

        private static void OnColumnHeaderClick(object sender, RoutedEventArgs e)
        {
            try
            {
                var columnHeader = e.OriginalSource as GridViewColumnHeader;
                if (columnHeader != null && GetCanUseSort(columnHeader.Column))
                {
                    DoSort((ListView)e.Source, columnHeader.Column);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
        }

        private static void DoSort(ListView listView, GridViewColumn newColumn)
        {
            try
            {
                var sortDescriptions = listView.Items.SortDescriptions;
                var newDirection = ListSortDirection.Ascending;

                var propertyPath = ResolveSortExpression(newColumn);
                if (propertyPath != null)
                {
                    if (sortDescriptions.Count > 0)
                    {
                        if (sortDescriptions[0].PropertyName == propertyPath)
                        {
                            newDirection = GetSortDirection(newColumn) == ListSortDirection.Ascending ?
                                ListSortDirection.Descending :
                                ListSortDirection.Ascending;
                        }
                        else
                        {
                            var gridView = (GridView)listView.View;
                            foreach (var column in gridView.Columns.Where(c => GetSortDirection(c) != null))
                            {
                                SetSortDirection(column, null);
                            }
                        }

                        sortDescriptions.Clear();
                    }

                    sortDescriptions.Add(new SortDescription(propertyPath, newDirection));
                    SetSortDirection(newColumn, newDirection);
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
        }

        private static string ResolveSortExpression(GridViewColumn column)
        {
            try
            {
                var propertyPath = GetSortExpression(column);
                if (propertyPath == null)
                {
                    var binding = column.DisplayMemberBinding as Binding;
                    return binding != null ? binding.Path.Path : null;
                }
                else
                {
                    return propertyPath;
                }
            }
            catch (Exception exc)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_SILENTERROR, exc);
            }
            return null;
        }
    }
}
